package cn.tedu.boot31.controller;

import cn.tedu.boot31.utils.DBUtils;
import cn.tedu.boot31.vo.Article;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

@Controller
public class ArticleController {

    @RequestMapping("/createArticle")
    @ResponseBody
    public String createArticle(Article article) {

        System.out.println("article = " + article);

        try (
                //获取数据库连接
                Connection conn = DBUtils.getConn();
        ) {
            //向数据库中写入数据
            String sql = "insert into article values(null,?,?,?)";
            //预编译SQL语句
            PreparedStatement ps = conn.prepareStatement(sql);
            //替换SQL语句中的?
            ps.setString(1, article.getTitle());
            ps.setString(2, article.getAuthor());
            ps.setString(3, article.getContent());
            ps.executeUpdate(); //执行
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return "添加完成";
    }

    @RequestMapping("/showAllArticle")
    @ResponseBody
    public String showAllArticle(){
        ArrayList<Article> list = new ArrayList<>();
        //获取连接
        try (Connection conn = DBUtils.getConn()){
            String sql = "select * from article";
            PreparedStatement ps = conn.prepareStatement(sql);
            ResultSet rs = ps.executeQuery();
            //遍历结果集
            while(rs.next()){
                String title = rs.getString(2);
                String author = rs.getString(3);
                String content = rs.getString(4);
                list.add(new Article(title,author,content));
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }

        //把集合中的内容以字符串形式返回个客户端
        return list.toString();
    }
}
